package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author hlx
 * @date 2022/12/10 0010
 * @apiNote
 */
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    /**
     * 查询文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //1.校验参数
        if (null == dto) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        dto.checkParam();

        WmUser user = WmThreadLocalUtil.getUser();
        if (null == user) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.设置分页参数
        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        //3.设置查询条件
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (null != dto.getStatus()) {
            lambdaQueryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }

        if (null != dto.getChannelId()) {
            lambdaQueryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }

        if (StringUtils.isNotEmpty(dto.getKeyword())) {
            lambdaQueryWrapper.like(WmNews::getTitle, dto.getKeyword());
        }

        if (null != dto.getBeginPubDate() && null != dto.getEndPubDate()) {
            lambdaQueryWrapper.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }

        //4.查询数据
        page(page, lambdaQueryWrapper);

        //5.封装返回结果
        PageResponseResult pageResponseResult = new PageResponseResult();
        pageResponseResult.setTotal((int) page.getTotal());
        pageResponseResult.setData(page.getRecords());

        pageResponseResult.setCurrentPage(dto.getPage());
        pageResponseResult.setSize(dto.getSize());

        return pageResponseResult;
    }

    /**
     * 发布文章或保存草稿
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto dto) {
        //1.校验参数是否合法，不合法返回错误信息
        if (null == dto || StringUtils.isEmpty(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        WmUser user = WmThreadLocalUtil.getUser();
        if (null == user) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.保存或更新文章内容
        WmNews wmNews = saveOrUpdateNews(dto, user);

        //2.1如果是保存草稿则返回成功
        if (dto.getStatus().equals(WmNews.Status.NORMAL.getCode())) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //2.2抽取内容中的所有图片
        List<String> urls = ectractUrlInfo(dto.getContent());

        //3.保存内容图片与素材之间的关系
        saveRelativeInfoForContent(urls, wmNews);

        //4.保存封面图片与素材之间的关系
        saveRelativeInfoForCover(urls, wmNews, dto);
        //5.返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 保存封面图片和素材之间的关系
     *
     * @param urls
     * @param wmNews
     * @param dto
     */
    private void saveRelativeInfoForCover(List<String> urls, WmNews wmNews, WmNewsDto dto) {
        //1.获取传递过来的封面图片
        List<String> images = dto.getImages();
        //1.1处理封面为自动的情况
        if (dto.getType() == -1) {
            if (null == urls || urls.size() == 0) {
                wmNews.setType((short) 0);
            } else if (urls.size() < 3) {
                wmNews.setType((short) 1);
                images = urls.stream().limit(1).collect(Collectors.toList());
            } else {
                wmNews.setType((short) 3);
                images = urls.stream().limit(3).collect(Collectors.toList());
            }
            //更新文章封面的类型
            updateById(wmNews);
        }

        //判断封面是否是无图
        if (null != urls && urls.size() > 0) {
            //保存关联关系
            saveRelativeInfo(urls, wmNews, (byte) 1);

        }

    }

    /**
     * 保存文章内容和素材之间的关系
     *
     * @param urls
     * @param wmNews
     */
    private void saveRelativeInfoForContent(List<String> urls, WmNews wmNews) {
        saveRelativeInfo(urls, wmNews, (byte) 0);
    }

    private void saveRelativeInfo(List<String> urls, WmNews wmNews, byte type) {
        //1.对url进行去重
        urls = urls.stream().distinct().collect(Collectors.toList());

        //2.通过URL地址查询素材的id
        List<WmMaterial> wmMaterials = wmMaterialMapper
                .selectList(Wrappers.<WmMaterial>lambdaQuery()
                        .in(WmMaterial::getUrl, urls)
                        .select(WmMaterial::getId));

        List<Integer> ids = wmMaterials.stream().map(item -> item.getId()).collect(Collectors.toList());


        //3.判断素材是否有被删除过
        if (null == ids || ids.size() != urls.size()) {
            throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL);
        }

        //4.批量保存文章和素材之间的关系
        wmNewsMaterialMapper.batchInsert(wmNews.getId(), ids, type);
    }

    /**
     * 抽取文章内容中的图片地址
     *
     * @param content
     * @return
     */
    private List<String> ectractUrlInfo(String content) {
        List<String> urls = new ArrayList<>();
        List<Map> list = JSON.parseArray(content, Map.class);

        if (null != list && list.size() > 0) {
            for (Map map : list) {
                if (map.get("type").equals("image")) {
                    urls.add(map.get("value").toString());
                }
            }
        }
        return urls;
    }

    /**
     * 保存或更新文章数据
     *
     * @param dto
     * @param wmUser
     */
    private WmNews saveOrUpdateNews(WmNewsDto dto, WmUser wmUser) {
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        //处理图片
        String images = StringUtils.join(dto.getImages().toArray(), ",");
        wmNews.setImages(images);
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        //处理自动-数据库使用了unsigned修饰不能存储负数
        if (dto.getType() == -1) {
            wmNews.setType(null);
        }

        //文章更新
        if (null == dto.getId()) {
            save(wmNews);
        } else {
            //文章修改
            //删除文章和素材之间的关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,
                    dto.getId()));
            updateById(wmNews);
        }
        return wmNews;
    }

}
